import React, { useEffect, useState, useMemo, useCallback } from 'react';

// 导入所有页面组件
import DashboardContent from '../pages/DashboardContent';
import FocusMode from '../pages/FocusMode';
import StudyPlan from '../pages/StudyPlan';
import Friends from '../pages/Friends';
import Chat from '../pages/Chat';
import AIChat from '../pages/AIChat';
import CloudStorage from '../pages/CloudStorage';
import CareerPlan from '../pages/CareerPlan';
import Profile from '../pages/Profile';
import Settings from '../pages/Settings';

interface PagePreloadManagerProps {
  children: React.ReactNode;
}

const PagePreloadManager: React.FC<PagePreloadManagerProps> = ({ children }) => {
  const [preloadProgress, setPreloadProgress] = useState(0);
  const [isPreloading, setIsPreloading] = useState(true);
  const [preloadedPages, setPreloadedPages] = useState<Set<string>>(new Set());

  // 定义所有需要预加载的页面 - 使用useMemo避免重复创建
  const pagesToPreload = useMemo(() => [
    { path: '/dashboard', component: DashboardContent },
    { path: '/focus', component: FocusMode },
    { path: '/study', component: StudyPlan },
    { path: '/friends', component: Friends },
    { path: '/chat', component: Chat },
    { path: '/ai', component: AIChat },
    { path: '/cloud', component: CloudStorage },
    { path: '/career', component: CareerPlan },
    { path: '/profile', component: Profile },
    { path: '/settings', component: Settings }
  ], []);

  // 简化的预加载函数
  const preloadPage = useCallback(async (path: string, component: React.ComponentType<any>) => {
    // 模拟预加载延迟
    await new Promise(resolve => setTimeout(resolve, 100));
    setPreloadedPages(prev => {
      const newSet = new Set(prev);
      newSet.add(path);
      return newSet;
    });
  }, []);

  useEffect(() => {
    const preloadAllPages = async () => {
      const totalPages = pagesToPreload.length;
      let loadedCount = 0;

      // 并行预加载所有页面，但添加延迟避免阻塞
      const preloadPromises = pagesToPreload.map((page, index) => {
        return new Promise<void>((resolve) => {
          setTimeout(async () => {
            await preloadPage(page.path, page.component);
            loadedCount++;
            setPreloadProgress(Math.round((loadedCount / totalPages) * 100));
            resolve();
          }, index * 200); // 每个页面间隔200ms预加载
        });
      });

      await Promise.all(preloadPromises);
      
      // 预加载完成
      setTimeout(() => {
        setIsPreloading(false);
      }, 500);
    };

    preloadAllPages();
  }, [pagesToPreload, preloadPage]);

  // 如果正在预加载，显示进度
  if (isPreloading) {
    return (
      <div style={{
        position: 'fixed',
        top: 0,
        left: 0,
        right: 0,
        bottom: 0,
        background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
        display: 'flex',
        flexDirection: 'column',
        justifyContent: 'center',
        alignItems: 'center',
        color: 'white',
        zIndex: 9999
      }}>
        <div style={{ textAlign: 'center' }}>
          <div style={{ fontSize: '24px', marginBottom: '20px', fontWeight: 'bold' }}>
            LinkMate
          </div>
          <div style={{ fontSize: '16px', marginBottom: '30px' }}>
            正在预加载页面...
          </div>
          
          {/* 进度条 */}
          <div style={{
            width: '300px',
            height: '6px',
            background: 'rgba(255, 255, 255, 0.3)',
            borderRadius: '3px',
            overflow: 'hidden',
            marginBottom: '20px'
          }}>
            <div style={{
              width: `${preloadProgress}%`,
              height: '100%',
              background: 'white',
              borderRadius: '3px',
              transition: 'width 0.3s ease'
            }} />
          </div>
          
          <div style={{ fontSize: '14px', opacity: 0.8 }}>
            {preloadProgress}% 完成
          </div>
          
          <div style={{ fontSize: '12px', marginTop: '20px', opacity: 0.6 }}>
            已预加载 {preloadedPages.size} 个页面
          </div>
        </div>
      </div>
    );
  }

  return <>{children}</>;
};

export default PagePreloadManager;
